package quartz.job;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Service;
import org.springframework.util.MethodInvoker;
import quartz.util.SpringUtil;

import java.lang.reflect.InvocationTargetException;

@Service
public class JobExecutor implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();
        Class<?> clazz = null;
        try {
            clazz = Class.forName((String) jobDataMap.get("classPath"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Object targetObj = SpringUtil.getBean(clazz);
        MethodInvoker methodInvoker  = new MethodInvoker();
        methodInvoker.setTargetObject(targetObj);
        methodInvoker.setTargetMethod((String) jobDataMap.get("targetMethod"));
//        if (!StringUtils.isEmpty(arguments)) {
//            methodInvoker.setArguments(arguments.split(","));
//        }
        try {
            methodInvoker.prepare();
            methodInvoker.invoke();
        } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
